package com.sinosoft.emplmis.application.web;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sinosoft.framework.core.api.domain.UserOrgData;
import com.sinosoft.framework.core.api.service.UserOrgService;
import com.sinosoft.framework.security.utils.SecurityUtil;

@Controller
@RequestMapping("/")
public class LoginController {

	/**
	 * 用户机构服务类
	 */
	@Autowired
	private UserOrgService userOrgService;

	/**
	 * 默认页面
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String index(Model model) {
		model.addAttribute("loginName", SecurityUtil.getLoginName());
		UserOrgData userOrgData = userOrgService.getUserOrgByUserName(SecurityUtil.getLoginName());
		if(null != userOrgData)
		{
			Session session = SecurityUtils.getSubject().getSession();
			session.setAttribute("userOrg", userOrgData);
		}
		return "app/index";
	}
	
	@RequestMapping(value="getLogin", method = RequestMethod.GET)
	@ResponseBody
	public String getLoginName(){
		return SecurityUtil.getLoginName();
	}
	
	/**
	 * 登录页面
	 * @return
	 */
	@RequestMapping(value="login", method = RequestMethod.GET)
	public String login() {
		if(SecurityUtil.isLogin()) {
			return "redirect:/";
		}
		return "app/login";
	}
	
	@RequestMapping(value="login", method = RequestMethod.POST)
	public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
		return "app/login";
	}
	
	@RequestMapping(value="logout", method = RequestMethod.POST)
	@ResponseBody
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "success";
	}
}
